﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using System.Windows.Forms;
using AL.Common;
using AL.Entity;
using AL.Helper;
using AL.ViewModel;
using mshtml;
using Newtonsoft.Json;
using Config = AL.Helper.Config;

namespace AL
{
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }


        private AccountModel _accountModel = new AccountModel();
        // 窗体初始化
        private void FormMain_Load(object sender, EventArgs e)
        {
            const string url = "http://wx.qq.com/";
            webBrowser1.ScriptErrorsSuppressed = true;
            webBrowser1.Navigate(url);

            // 加载公众帐号列表
            LoadTreeNode();

            // 设置默认排序
            toolStripComboBox_OrderType.SelectedIndex = 0;

            // 开启文章列表浏览器
            webBrowser2.ObjectForScripting = this;
            webBrowser2.ScriptErrorsSuppressed = true;
            webBrowser2.IsWebBrowserContextMenuEnabled = false;
            webBrowser2.Navigate(string.Format(@"{0}\Templates\ArticleList.html", Config.RootPath));
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            CheckLogin();
            CacheHelper.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
            //MessageBox.Show("timer");
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                timer1.Enabled = true;
            }
        }


        #region 浏览器交互方法

        //private string _returnJson = "{ error: {0}, message: {1}, data: {2} }";

        private bool _isWorking = false;
        // 浏览器交互方法：登录控制
        public string CheckLogin()
        {
            var ret =  "{ error: true, message: '帐号未登录', data: [] }";
            if (_isWorking) { return "{ error: true, message: '登录中...', data: [] }"; }

            _isWorking = true;
            _accountModel = LoginHelper.CheckLogin(webBrowser1);

            if (_accountModel.IsLogined && !_accountModel.IsLoaded)
            {
                toolStripSplitButton_Avatar.Text = string.Format(" {0}", _accountModel.NickName);

                try
                {
                    // 获取保存头像
                    var bitmap = LoginHelper.GetImage(ref webBrowser1, "", _accountModel.AvatarUrl, "");
                    if (bitmap != null)
                    {
                        // 关闭循环检测
                        timer1.Enabled = false;
                        _accountModel.IsLoaded = true;

                        toolStripSplitButton_Avatar.Image = new Bitmap(bitmap, 48, 48);

                        var path = Config.RootPath;
                        path = string.Format(@"{0}\Avatars\", path);

                        var filePath = string.Format("{0}{1}.png", path, _accountModel.UserName);
                        bitmap.Save(filePath, ImageFormat.Png);

                        LoginHelper.Authorization(_accountModel);
                        ret = string.Format("{{ error: true, message: '登录成功', data: {0} }}",
                            JsonConvert.SerializeObject(_accountModel));
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }

            _isWorking = false;
            return ret;
        }

        // 浏览器交互方法： 获取文章列表数据
        public string GetArticleList(int page)
        {
            //if (!_accountModel.IsLogined || !_accountModel.IsLoaded) return "{ error: true, message: '帐号未登录', data: [] }";
            var ret = "{ error: true, message: '无数据', data: [], account: [] }";

            if (string.IsNullOrWhiteSpace(_currentNodeId) || _currentNodeId == "root")
            {
                return ret;
            }
            else
            {
                _lastNodeId = _currentNodeId;
            }

            ret = GetArticleList(_currentNodeId, page);

            return ret;
        }

        private string GetArticleList(string openId, int page)
        {
            //if (!_accountModel.IsLogined || !_accountModel.IsLoaded) return "{ error: true, message: '帐号未登录', data: [] }";
            var account = CacheHolder.GetAccount(openId);
            
            return GetArticleList(account, page);
        }

        private string GetArticleList(Account account, int page)
        {
            //if (!_accountModel.IsLogined || !_accountModel.IsLoaded) return "{ error: true, message: '帐号未登录', data: [] }";
            var ret = "{ error: true, message: '无数据', data: [], account: [] }";
            if (!LoginHelper.Authorization(_accountModel)) return ret;

            //StartLoading();
            CacheHelper.MaxCount = 1000;
            CacheHelper.CurrentCount = 0;
            CacheHelper.OpenId = account.OpenId;
            CacheHelper.LoginCookies = LoginHelper.GetCookieString(webBrowser1);

            LoadingForm = new FormLoading();
            LoadingForm.Width = this.Width;
            LoadingForm.Height = this.Height;
            LoadingForm.StartPosition = FormStartPosition.CenterParent;
            LoadingForm.ShowDialog();

            //// 根据公众号获取文章列表
            //_accountModel.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
            //var articles = CacheHolder.GetArticles(account.OpenId, page, _accountModel.LoginCookies);

            //SpinWait.SpinUntil(() => CacheHelper.MaxCount == CacheHelper.CurrentCount, 300 );

            var articles = CacheHelper.Articles;
            if (articles.Any())
            {
                ret = string.Format("{{ error: false, message: '请求成功', data: {0}, account: {1} }}", JsonConvert.SerializeObject(articles), JsonConvert.SerializeObject(account));
            }

            //StopLoading();
            return ret;
        }

        public FormLoading LoadingForm = new FormLoading();


        // 浏览器交互方法： 获取正文
        public string GetArticle(string title, string articleUrl)
        {
            //if (!_accountModel.IsLogined || !_accountModel.IsLoaded) return "{ error: true, message: '帐号未登录', data: [] }";
            var ret = "{ error: false, message: '网页跳转模式，无数据', data: [] }";
            if (!LoginHelper.Authorization(_accountModel)) return ret;

            //string arg = HttpUtility.UrlEncode(articleUrl);
            //string url = string.Format("https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxcheckurl?requrl={0}", arg);

            // 用默认浏览器打开链接
            WebBrowserHelper.ShellExecute(IntPtr.Zero, "open", articleUrl, "", "", 4);
            return ret;
        }



        // 浏览器交互方法： 获取文章统计
        public string GetArticleCount(string articleId)
        {
            var ret = "{ error: false, message: '无数据', data: [] }";
            if (!LoginHelper.Authorization(_accountModel)) return ret;

            _accountModel.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
            var article = CacheHolder.GetArticle(articleId, _accountModel.LoginCookies);
            if (article != null)
            {
                var obj = new { article.ReadingCount, article.PraiseCount };
                ret = string.Format("{{ error: false, message: '请求成功', data: {0} }}", JsonConvert.SerializeObject(obj));
            }

            return ret;
        }

        #endregion


        private string _currentNodeId = "root";
        private string _lastNodeId = string.Empty;
        // 树选项切换
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var nodeId = e.Node.Name;
            var nodeText = e.Node.Text;

            _currentNodeId = nodeId;
            if (nodeId == "root")
            {
                panel_Article_Area.Visible = false;
                label_PublicAccountName.Text = "";
            }
            else if (nodeId != "root")
            {
                panel_Article_Area.Visible = true;
                label_PublicAccountName.Text = nodeText;

                // 刷新 HistoryPages
                //var historyPage = CacheHolder.GetHistoryPage(_currentNodeId, 1, false);
                var cacheKey = string.Format("{0}_{1}", _currentNodeId, 1);
                var historyPage = CacheHelper.GetCache(cacheKey);
                if (historyPage == null)
                {
                    _accountModel.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
                    CacheHolder.RefreshHistoryPagesByOpenId(_currentNodeId, EnumType.SearchType.Week, _accountModel.LoginCookies);
                }

                if (_lastNodeId != _currentNodeId)
                {
                    // 执行页面刷新
                    //webBrowser2.Stop();
                    //webBrowser2.Refresh();

                    // 触发网页内的脚本
                    webBrowser2.Document.InvokeScript("refresh");

                }

                _lastNodeId = _currentNodeId;
            }
        }


        // 排序方式变更
        private void toolStripComboBox_OrderType_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 刷新当前页面排序
            CacheHolder.OrderType = toolStripComboBox_OrderType.SelectedIndex;

            if (!string.IsNullOrWhiteSpace(_currentNodeId) && _currentNodeId != "root")
            {
                // 触发网页内的脚本
                webBrowser2.Document.InvokeScript("refresh");
            }
        }


        // 显示微信主页
        private void toolStripSplitButton_Avatar_Click(object sender, EventArgs e)
        {
            panel_Article_Area.Visible = false;
            treeView1.SelectedNode = treeView1.Nodes[0];
        }

        private readonly FormAddPublicAccount _addPublicAccountForm = new FormAddPublicAccount();
        // 添加公众帐号
        private void toolStripButton_AddAccount_Click(object sender, EventArgs e)
        {
            if (!LoginHelper.Authorization(_accountModel)) return;

            var result = _addPublicAccountForm.ShowDialog();
            if (result == DialogResult.OK)
            {
                //MessageBox.Show("OK");

                // TODO: 刷新 treeview 列表
                LoadTreeNode();
            }


        }


        // 加载公众帐号列表
        private void LoadTreeNode()
        {
            var rootNode = treeView1.Nodes[0];
            rootNode.Nodes.Clear();

            var accounts = CacheHolder.GetAccounts();

            //// 加载所有公众号到根节点
            //if (accounts != null)
            //{
            //    foreach (var account in accounts)
            //    {
            //        var node = new TreeNode {Name = account.OpenId, Text = account.Name};
            //        rootNode.Nodes.Add(node);
            //    }
            //}

            // 按类别加载公众帐号
            var categories = CacheHolder.GetCategories();
            foreach (var category in categories)
            {
                if (!string.IsNullOrWhiteSpace(category)){
                    var categoryNode = new TreeNode {Name = "root", Text = category, ImageIndex = 0 };
                    var classAccounts = accounts.Where(y => y.ClassName == category).ToList();
                    foreach (var classAccount in classAccounts)
                    {
                        var node = new TreeNode { Name = classAccount.OpenId, Text = classAccount.Name, ImageIndex = 1 };
                        categoryNode.Nodes.Add(node);
                    }

                    rootNode.Nodes.Add(categoryNode);
                }
            }

            if (accounts == null) return;
            var rootAccounts = accounts.Where(y => y.ClassName == string.Empty).ToList();
            foreach (var classAccount in rootAccounts)
            {
                var node = new TreeNode { Name = classAccount.OpenId, Text = classAccount.Name, ImageIndex = 1 };
                rootNode.Nodes.Add(node);
            }

        }

        // 删除当前节点对应的公众帐号
        private void btn_DeletePublicAccount_Click(object sender, EventArgs e)
        {
            if (_currentNodeId != "root")
            {
                if (MessageBox.Show(@"是否删除该公众号？", @"警告：", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    CacheHolder.DeleteAccount(_currentNodeId);
                    LoadTreeNode();
                }
            }
        }

        // 退出登录
        private void toolStripMenuItem_Logout_Click(object sender, EventArgs e)
        {
            if (_accountModel.IsLoaded && _accountModel.IsLogined)
            {
                // 此方法无效
                //var htmlDocument = webBrowser1.Document;
                //var profileElement = htmlDocument.GetElementById("profile");
                //foreach (HtmlElement item in profileElement.All)
                //{
                //    var tagName = item.TagName.ToUpper();
                //    if (tagName == "A" && item.OuterHtml.Contains("iconLogout") && item.OuterHtml.Contains("class="))
                //    {
                //        item.InvokeMember("click");
                //        break;
                //    }
                //}

                var sb = new StringBuilder("$('.iconLogout').trigger('click'); $('.btn.chatSend').trigger('click');");
                var win = (IHTMLWindow2)webBrowser1.Document.Window.DomWindow;
                win.execScript(sb.ToString(), "Javascript");

                timer1.Enabled = true;
                toolStripSplitButton_Avatar.Text = string.Format(" {0}", "登录微信");
                toolStripSplitButton_Avatar.Image = AL.Properties.Resources.Avatar;
            }
        }

        // 清除缓存数据
        private void btn_ClearArticles_Click(object sender, EventArgs e)
        {
            var title = "所有公众号";
            var account = CacheHolder.GetAccount(_currentNodeId);
            if (account != null) title = account.Name;

            if (MessageBox.Show(string.Format("是否清除 {0} 的缓存数据", title), @"警 告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                CacheHolder.ClearArticlesByOpenId(_currentNodeId);
                MessageBox.Show(@"清除缓存成功");
            }
        }

        private void toolStripButton_ClearArticles_Click(object sender, EventArgs e)
        {
            var title = "所有公众号";
            if (MessageBox.Show(string.Format("是否清除 {0} 的缓存数据", title), @"警 告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                CacheHolder.ClearArticlesByOpenId(_currentNodeId);
                MessageBox.Show(@"清除缓存成功");
            }
        }

        // 全部刷新月数据
        private void toolStripButton_RefreshAll_Click(object sender, EventArgs e)
        {
            //StartLoading();

            var accounts = CacheHolder.GetAccounts();
            foreach (var account in accounts)
            {
                _accountModel.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
                CacheHolder.RefreshHistoryPagesByOpenId(account.OpenId, EnumType.SearchType.Month, _accountModel.LoginCookies);
                CacheHelper.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
            }

            CacheHelper.CurrentCount = 0;
            CacheHelper.OpenId = string.Empty;

            LoadingForm = new FormLoading();
            LoadingForm.Width = this.Width;
            LoadingForm.Height = this.Height;
            LoadingForm.StartPosition = FormStartPosition.CenterParent;
            LoadingForm.ShowDialog();

            //StopLoading();
            MessageBox.Show(@"全部刷新成功");
        }

        // 全部刷新周数据
        private void toolStripButton_RefreshAllWeek_Click(object sender, EventArgs e)
        {
            var accounts = CacheHolder.GetAccounts();
            foreach (var account in accounts)
            {
                _accountModel.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
                CacheHolder.RefreshHistoryPagesByOpenId(account.OpenId, EnumType.SearchType.Week, _accountModel.LoginCookies);
                CacheHelper.LoginCookies = LoginHelper.GetCookieString(webBrowser1);
            }

            CacheHelper.CurrentCount = 0;
            CacheHelper.OpenId = string.Empty;

            LoadingForm = new FormLoading();
            LoadingForm.Width = this.Width;
            LoadingForm.Height = this.Height;
            LoadingForm.StartPosition = FormStartPosition.CenterParent;
            LoadingForm.ShowDialog();

            //StopLoading();
            MessageBox.Show(@"全部刷新成功");
        }




    }
}
